<template>
  <div class="app-container">
    <div class="top">
      <div class="title">新增工时</div>
      <el-button class="copy-btn" type="primary" @click="copyLastWeekFn" plain>复制一周</el-button>
    </div>
    <el-divider></el-divider>
    <div class="cont">

      <el-form ref="form" :model="workHoursData" label-width="0">
        <div class="workhour-row" v-for="(item,key) of workHoursData.propFormData" :key="key">
          <div class="title">
            {{'新增工时' + (key+1)}}
            <div class="title-link">
              <el-link type="primary" icon="el-icon-circle-plus" @click="rowCopyFn(key,item)">复制</el-link>
              <el-link type="info" icon="el-icon-error" @click="rowDeleteFn(key)">删除</el-link>
            </div>
          </div>
          <div class="form-div">
            <el-row>
              <el-col :span="4" :offset="1">
                <el-form-item :prop="'propFormData.' + key + '.projectId'" :rules="[{ required: true, message: '请选择项目', trigger: 'change' }]">
                  <el-select v-model="item.projectId" placeholder="请选择项目"  style="width:100%" @change="projectIdChangeFn($event,key)" >
                    <el-option v-for="dict in projectList" :key="dict.projectId" :label="dict.projectName" :value="dict.projectId"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4" :offset="2">
                <el-form-item :prop="'propFormData.' + key + '.workTypeSecond'" :rules="[{ required: true, message: '请选择工时分类', trigger: 'change' }]">
                  <el-select v-model="item.workTypeSecond" placeholder="请选择工时分类" style="width:100%" :disabled="item.disabled">
                    <el-option v-for="dict in ((typeCascadeData[item.approval || 0] || {}).children || [])" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                  </el-select>
                  <!-- <el-cascader style="width:100%" v-model="typeCascadeValue" :options="typeCascadeData" clearable></el-cascader> -->
                </el-form-item>
              </el-col>
              <el-col :span="4" :offset="2">
                <el-form-item :prop="'propFormData.' + key + '.startDate'" :rules="[{ required: true, message: '请填写日期', trigger: 'blur' }]">
                  <el-date-picker v-model="item.startDate" align="right" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width:100%" :picker-options="startDateOptions" :disabled="item.disabled">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="4" :offset="2">
                <el-form-item :prop="'propFormData.' + key + '.endTime'" :rules="[{ required: true, message: '请填写时间', trigger: 'blur' }]">
                  <el-time-picker is-range v-model="item.timeData" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围" style="width:100%" value-format="HH:mm" @change="timeDataChangeFn($event,key)" :disabled="item.disabled">
                  </el-time-picker>
                </el-form-item>
              </el-col>
              <el-col :span="4" :offset="1">
                <el-form-item :prop="'propFormData.' + key + '.workHourCount'" :rules="[{ required: true, message: '请填写工时', trigger: 'blur' }]">
                  <el-input-number v-model="item.workHourCount" controls-position="right" :step="0.1" :min="0.1" style="width:80%" :disabled="item.disabled"/> (小时)
                </el-form-item>
              </el-col>
              <el-col :span="16" :offset="2">
                <el-form-item :prop="'propFormData.' + key + '.workDesc'" :rules="[{ required: true, message: '请输入任务描述', trigger: 'blur' }]">
                  <el-input v-model="item.workDesc" type="text" maxlength="500" show-word-limit placeholder="请输入任务描述" style="width:100%" :disabled="item.disabled"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
    </div>
    <div class="foot-btn">
      <el-button type="primary" @click="submitFormFn">提交</el-button>
      <el-button @click="cancelFn">返回</el-button>
    </div>
  </div>

</template>

<script>
  import { apiWorkhourAddbatch, apiCopyLastWeekWorkHour, apiListbystatusProject, apiWorkhourTypeList } from "@/api/pmp/api.workhour";

  export default {
    name: 'workhourEditor',
    data () {
      var checkTime = (rule, value, callback) => {
        if (!this.timeData || !this.timeData[0] || !this.timeData[1]) {
          return callback(new Error('请选择时间'));
        }
        if (this.timeData[0] == this.timeData[1]) {
          return callback(new Error('开始时间和结束时间不能一样'));
        }
        return callback();
      };
      return {
        // 循环表单集合

        workHoursData:{
          propFormData:[
            {
              projectId:'',
              workType:'',
              startDate:'',
              disabled:true,
              approval:undefined,
              timeData:['9:00','18:00'],
              startTime:'9:00',
              endTime:'18:00',
              workHourCount:8,
              workDesc:''
            }
          ],
          // 用来验证
        },
        projectData:{},
        typeCascadeValue:[],
        typeCascadeData:[],
        projectList:[],
        timeData:[],
        dateRange: [],
        // 数据范围选项
        projectList: [
          {
            projectId: 0,
            projectName: "",
            salemanName: "",
            principalName: "",
            approval:0
          }
        ],
        queryParams: {
          excludeProjectStatus: "6,7"
        },
        // 日期配置
        startDateOptions: {
          // disabledDate(time) {
          //   let Nowdate=new Date();
          //   let WeekFirstDay=new Date(Nowdate-Nowdate.getDay()*86400000).getTime();
          //   return  WeekFirstDay >= time.getTime() || time.getTime() >= new Date((WeekFirstDay/1000+7*86400)*1000).getTime();
          // }
        },
        rulesTimeData: [{ validator: checkTime, trigger: 'blur,change' }]
      };
    },
    computed: {
      visitedViews (){
        console.log('TagsView页的visitedViews:',this.$store.state.tagsView.visitedViews);
        return this.$store.state.tagsView.visitedViews;
      }
    },
    created() {
      this.getProjectListFn();
      this.getWorkhourTypeListFn();
    },
    methods: {
      // 此方法固定关闭当前页面，并返回工时列表
      closePathFn(){
        if((this.visitedViews || []).find(item => item.name == "workhourEditor")) {
          this.$store.dispatch('tagsView/delView', (this.visitedViews || []).find(item => item.name == "workhourEditor"))
            .then(({ visitedViews }) => {
              this.$router.replace({ name: 'Workhour' });
            });
        }
      },
      // 单行复制方法
      rowCopyFn(key,item){
        this.workHoursData.propFormData.push(JSON.parse(JSON.stringify(item)));
      },
      // 单行删除方法
      rowDeleteFn(key){
        if((this.workHoursData.propFormData || []).length > 1){
          (this.workHoursData.propFormData || []).splice(key, 1);
        }else{
          this.msgError('请至少保留一条');
        }
      },
      // 选择项目下拉框
      projectIdChangeFn(selection,key) {
        let ids = this.projectList.find(item => item.projectId == selection);
        this.workHoursData.propFormData[key].approval = ids.approval || 0;
        this.workHoursData.propFormData[key].disabled = false;

        // 根据选择结果，解锁其他组件操作，并赋值approval

      },
      // 时间选择后处理逻辑
      timeDataChangeFn(selection,key) {
        if(selection){
          [this.workHoursData.propFormData[key].startTime, this.workHoursData.propFormData[key].endTime] = [selection[0], selection[1]];
        }else{
          [this.workHoursData.propFormData[key].startTime, this.workHoursData.propFormData[key].endTime] = ['', ''];
        }
      },
      // 返回按钮
      cancelFn() {
        this.closePathFn();
      },
      /** 提交按钮 */
      submitFormFn: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            apiWorkhourAddbatch(JSON.stringify(this.workHoursData.propFormData)).then(response => {
              if (response.code === 200) {
                this.msgSuccess("批量添加成功");
                this.closePathFn();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        });
      },
      // 获取项目列表
      getProjectListFn(){
        apiListbystatusProject(this.queryParams)
          .then(res => {
            this.loading = false;
            this.total = res.total;
            this.projectList = res.rows;
          });
      },
      // 获取项目分类列表
      getWorkhourTypeListFn(){
        apiWorkhourTypeList().then(res => {
          this.typeCascadeData = res.data;
        });
      },
      // 复制上周周报
      copyLastWeekFn(){
        apiCopyLastWeekWorkHour().then(response => {
          console.log('复制',response);
          if (response.code === 200) {
            if ((response.data || []).length > 0){
              this.msgSuccess("已复制，并覆盖现有数据");
              this.dataProcessingFn(response.data);
            }else{
              this.msgError("上周没有数据");
            }
          } else {
            this.msgError(response.msg);
          }
        });
      },
      dataProcessingFn(data){
        // 清空队列，然后赋值
        let propFormData = [];
        data.forEach((ele,key) => {
          propFormData.push({
            projectId: ele.projectId,
            workType: ele.workTypeSecond,
            startDate: ele.startDate,
            disabled: false,
            approval: ele.approval || 0,
            timeData: [ele.startTime || '9:00',ele.endTime || '18:00'],
            workHourCount: ele.workHourCount,
            workDesc: ele.workDesc
          });
        });
        this.workHoursData.propFormData = propFormData;

      }
    }
  };
</script>

<style lang="less" scoped>
  .app-container{
    padding: 0;
    height: 100%;
    .top{
      position: relative;
      padding: 20px 20px 0 20px ;
      .title{
        padding: 6px 0 5px 24px;
        font-size:18px;
        font-family:PingFangSC-Medium,PingFang SC;
        font-weight:500;
        color:rgba(51,51,51,1);
        line-height:25px;
      }
      .copy-btn{
        position:absolute;
        top:20px;
        right: 43px;
      }
    }
    .cont{
      display: flex;
      padding-top: 26px;
      width: 100%;
      height: 100%;
      // max-height: 800px;
      overflow-y:auto;
      form{
        width: 100%;
        .workhour-row{
          flex-grow:1;
          width: auto;
          height: 180px;
          margin: 0 40px 24px;
          .title{
            &::before{
              content: '*';
              color: #ff4949;
              margin-right: 4px;
            }
            position: relative;
            padding-left: 24px;
            width: 100%;
            height: 40px;
            background:rgba(244,244,244,1);
            border:1px solid rgba(232,232,232,1);
            font-size:14px;
            font-family:PingFangSC-Regular,PingFang SC;
            font-weight:400;
            color:rgba(51,51,51,1);
            line-height:40px;
            .title-link{
              position: absolute;
              top: 0px;
              right: 0px;
              a{
                margin-right: 25px;
                &:hover{

                }
              }
            }
          }
          .form-div{
            width: 100%;
            height: 140px;
            padding-top: 20px;
            border:1px solid rgba(232,232,232,1);
            border-top: none;
          }
        }
      }



    }
    .foot-btn{
      text-align: right;
      padding-right: 121px;
    }

  }
</style>
